#include "ui.h"

int initFiles() {
  src = fopen("../conf/text.ui", "r");
  css = fopen("../style/text.css","w");
  return 0;
}

int setBaseUI() {
  fprintf(css, ".gnoui * {\n\t%s\n\t%s\n\t%s\n\t%s\n}\n\n","height: auto;", "width: 100%;", "margin: 0px;", "padding: 0px;");
  return 0;
}

int setUIConf() {
  char opt[MAX_LINE];
  char *key, *val;
  char *del = ":";
  char *sec = "";
  char prev;

  if (src) {
    while (fgets(opt, MAX_LINE, src)) {
      if (opt[0] == SEC_HEAD) {
        if (prev != 0) {
          fprintf(css, "}\n\n");
        }
        sec = &opt[1];
        writeHead(sec);
      } else if (opt[0] != '\n') {
        key = strtok(opt, del);
        val = strtok(NULL, del);
        writeVal(key,val);
      }
      prev = opt[0];
    } //end while
    fprintf(css, "}");
    return 0;
  }
  return 1;
}

int writeHead(char *sec) {
  int i = 0;
  while (sec[i] != '\n') {
    sec[i] = tolower(sec[i]);
    ++i;
  }
  sec[i] = 0;
  fprintf(css, ".gnoui .post-%s {\n", sec);
  return 0;
}

int writeVal(char *k, char *v) {
  int i = 0;
  while (v[i] != '\n' && v[i] != 0) {
    v[i] = tolower(v[i]);
    ++i;
  }
  v[i] = 0;

  if (!strcmp(k,"FONT")) {
    fprintf(css, "\tfont-family: %s, serif;\n", v);
  } else if (!strcmp(k,"SIZE")) {
    fprintf(css, "\tfont-size: %s%s;\n", v, UNITS);
  } else if (!strcmp(k,"SPACE")) {
    fprintf(css, "\tline-height: %s%s;\n", v, UNITS);
  } else if (!strcmp(k,"COLOR")) {
    fprintf(css, "\tcolor: %s;\n", v);
  }
  return 0;
}

int dinitFiles() {
  fclose(src);
  fclose(css);
  return 0;
}

int main () {
  if (initFiles() == 0) {
    setBaseUI();
    setUIConf();
    dinitFiles();
    return 0;
  }
  return 1;
}
